/*
 * Licensed Materials - Property of tenxcloud.com
 * (C) Copyright 2023 TenxCloud. All Rights Reserved.
 * 2023-02-1  @author ms.xie
 */

package utils

import (
	"fmt"
	"render-controller/v1alpha1"

	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/util/flowcontrol"
	"k8s.io/klog/v2"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/client/config"
)

const (
	K8S_REST_CONFIG_QPS   = 50
	K8S_REST_CONFIG_BURST = K8S_REST_CONFIG_QPS * 2
)

func NewK8sClient() (client.Client, error) {
	if err := v1alpha1.AddToScheme(scheme.Scheme); err != nil {
		klog.Error(err)
	}

	config, err2 := GetClientConfig()
	if err2 != nil {
		return nil, err2
	}

	client, err := client.New(config, client.Options{})
	if err != nil {
		klog.Errorf("get client failed, error %v", err)
		return nil, err
	}
	return client, nil
}

func GetClientConfig() (*rest.Config, error) {
	config, err := config.GetConfig()
	if err != nil {
		klog.Errorf("get config failed, error %v", err)
		return nil, err
	}
	config.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(float32(K8S_REST_CONFIG_QPS), K8S_REST_CONFIG_BURST)
	return config, nil
}

func GetTenantNS(name string) string {
	return name
}

func GetTenantSA(name string) string {
	return fmt.Sprintf("tenant-sa-%s", name)
}

func GetTenantRole(name string) string {
	return fmt.Sprintf("tenant-role-%s", name)
}

func GetTenantRoleBinding(name string) string {
	return fmt.Sprintf("tenant-rolebinding-%s", name)
}
